package com.carsite.webapp.action;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.carsite.Constants;
import com.carsite.model.Branch;
import com.carsite.model.ModuleMenu;
import com.carsite.model.Role;
import com.carsite.model.User;
import com.carsite.service.BranchManager;
import com.carsite.service.DepartmentManager;
import com.carsite.service.ModuleMenuManager;
import com.carsite.webapp.form.BranchForm;
import com.carsite.webapp.form.ModuleMenuForm;

/**
 * Action class to handle CRUD on a Branch object
 * 
 * @struts.action name="branchForm" path="/branchs" scope="request"
 *                validate="false" parameter="method" input="mainMenu"
 *             
 * @struts.action name="branchForm" path="/editBranch" scope="request"
 *                validate="false" parameter="method" input="list"
 * @struts.action name="branchForm" path="/saveBranch" scope="request"
 *                validate="true" parameter="method" input="edit"
 * @struts.action-set-property property="cancellable" value="true"
 * @struts.action-forward name="edit" path="/WEB-INF/pages/branchForm.jsp"
 * @struts.action-forward name="list" path="/WEB-INF/pages/branchList.jsp"
 * @struts.action-forward name="branchDeptTree"
 *                        path="/WEB-INF/pages/branchDeptTree.jsp"
 * @struts.action-forward name="search" path="/branchs.html" redirect="true"
 * @struts.action-forward name="bBSDeptTree" path="/WEB-INF/pages/bBSDeptTree.jsp"
 * @struts.action-forward name="treeSelect" path="/WEB-INF/pages/treeSelect.jsp"
 * 
 * 
 */
public final class BranchAction extends BaseAction {
	public ActionForward cancel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("search");
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'delete' method");
		}
		if (!this.check(request)) {
			return null;
		}
		ActionMessages messages = new ActionMessages();
		BranchForm branchForm = (BranchForm) form;

		// Exceptions are caught by ActionExceptionHandler
		BranchManager mgr = (BranchManager) getBean("branchManager");
		mgr.removeBranch(branchForm.getBranchId());

		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"branch.deleted"));

		// save messages in session, so they'll survive the redirect
		saveMessages(request.getSession(), messages);

		List topBranchList = mgr.getTopBranchs();
		request.setAttribute(Constants.BRANCH_LIST, topBranchList);

		branchForm = new BranchForm();
		updateFormBean(mapping, request, branchForm);
		;
		

		return mapping.findForward("edit");

	}

	

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'edit' method");
		}
		if (!this.check(request)) {
			return null;
		}
		BranchForm branchForm = (BranchForm) form;

		BranchManager mgr = (BranchManager) getBean("branchManager");

		if (branchForm.getBranchId() != null) {

			Branch branch = mgr.getBranch(branchForm.getBranchId());
            branchForm = (BranchForm) convert(branch);
            
            // if parent is null,be top menu.
            if(branch.getParent()!=null){
            	branchForm.setParentId(String.valueOf(branch.getParent().getBranchId()));
            	branchForm.setParentName(branch.getParent().getBranchName());	
            }
           
            updateFormBean(mapping, request, branchForm);
        }else {
         	
        	// default parent
         	if(branchForm.getParentId()!=null){
         		Branch branch = mgr.getBranch(branchForm.getParentId());
         	    branchForm.setParentId(String.valueOf(branch.getBranchId()));
             	branchForm.setParentName(branch.getBranchName());
             }	
         }
        
        List topBranchList = mgr.getTopBranchs();
        request.setAttribute(Constants.BRANCH_LIST,topBranchList);


        return mapping.findForward("edit");
        
        
    }

    public ActionForward save(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'save' method");
        }
        if(!this.check(request)){
        	return null;
        }
        // Extract attributes and parameters we will need
        ActionMessages messages = new ActionMessages();
        BranchForm branchForm = (BranchForm) form;
        boolean isNew = ("".equals(branchForm.getBranchId()) || branchForm.getBranchId() == null);

        BranchManager mgr = (BranchManager) getBean("branchManager");
        Branch branch = (Branch) convert(branchForm);
        
        
        if(isNew){
            
            if(branchForm.getParentId()!=null && !"".equals(branchForm.getParentId())){
            
            	Branch parent =  mgr.getBranch(branchForm.getParentId());
            	branch.setParent(parent);
            }
            
            mgr.saveBranch(branch);
            
        }else{
        	
        	Branch dbBranch = mgr.getBranch(branchForm.getBranchId());
        	        
        	dbBranch.setBranchName(branchForm.getBranchName());
        	dbBranch.setAddress(branchForm.getAddress());
        	dbBranch.setTelNo(branchForm.getTelNo());
        	
            if(branchForm.getParentId()!=null && !"".equals(branchForm.getParentId())){
            	
            	String dbParentBranchId = null;
            	if(dbBranch.getParent()!=null){
            		dbParentBranchId= String.valueOf(dbBranch.getParent().getBranchId());
            	}
                
            	if(!branchForm.getParentId().equals(dbParentBranchId)){
            		
            		Branch parent =  mgr.getBranch(branchForm.getParentId());
            		dbBranch.setParent(parent);
            	}
            }else{
            	dbBranch.setParent(null);
            }
            
            
            mgr.saveBranch(dbBranch);
        	
        }
      
        
        

        // add success messages
        if (isNew) {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("branch.added"));

            // save messages in session to survive a redirect
            saveMessages(request.getSession(), messages);

        } else {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("branch.updated"));
            saveMessages(request, messages);

            
        }
        
        
        
        //return to empty edit page
        branchForm = new BranchForm();
        updateFormBean(mapping, request, branchForm);
        
        List topBranchList = mgr.getTopBranchs();
        request.setAttribute(Constants.BRANCH_LIST,topBranchList);
        
        return mapping.findForward("edit");
        
        
        
    }

    public ActionForward search(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'search' method");
        }

        BranchForm branchForm = (BranchForm) form;
        Branch branch = (Branch) convert(branchForm);

        BranchManager mgr = (BranchManager) getBean("branchManager");
        request.setAttribute(Constants.BRANCH_LIST, mgr.getBranchs(branch));

        return mapping.findForward("list");
    }
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
            throws Exception {
        return search(mapping, form, request, response);
    }
    
    
    
    
    public ActionForward branchDeptTree(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
	throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'branchDeptTree' method");
		}
		
		
		BranchManager mgr = (BranchManager) getBean("branchManager");
		
		List topBranchList = mgr.getTopBranchs();
		
		request.setAttribute(Constants.BRANCH_LIST,topBranchList);
	    
		/*Iterator it = topBranchList.iterator();
		String branchDeptStr = createBranchDeptStr(it,deptMgr);
	    request.setAttribute("branchDeptStr",branchDeptStr);
	    */
        return mapping.findForward("branchDeptTree");
		  
	}
    public ActionForward bBSDeptTree(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
	throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'bBSDeptTree' method");
		}
		
		
		BranchManager mgr = (BranchManager) getBean("branchManager");
		
		List topBranchList = mgr.getTopBranchs();
		
		request.setAttribute(Constants.BRANCH_LIST,topBranchList);
	    
		/*Iterator it = topBranchList.iterator();
		String branchDeptStr = createBranchDeptStr(it,deptMgr);
	    request.setAttribute("branchDeptStr",branchDeptStr);
	    */
        return mapping.findForward("bBSDeptTree");
		  
	}
    public ActionForward treeSelect(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
	throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'bBSDeptTree' method");
		}
		BranchManager mgr = (BranchManager) getBean("branchManager");
		List topBranchList = mgr.getTopBranchs();
		request.setAttribute(Constants.BRANCH_LIST,topBranchList);
        return mapping.findForward("treeSelect");
		  
	}
    public String createBranchDeptStr(Iterator it,DepartmentManager deptMgr)
	        throws Exception {
		
    	
    	
    	
		String branchDeptStr =  null;
		      
	
		return branchDeptStr;
		  
	}
    public boolean check(HttpServletRequest request){
		 HttpSession session=request.getSession();
		 if(session==null){
			 return false;
		 }else{
			 User currentUser=(User)session.getAttribute("currentUser");
			 if(currentUser==null){
				 return false;
			 }else{
				 Set roles=currentUser.getRoles();
				 Iterator rolesIt=(Iterator)roles.iterator();
				 while(rolesIt.hasNext()){
					 
					 Role role=(Role)rolesIt.next();
					 if(role.getName().equals("admin")){
						 return true;
					 }
				 }
				 return false;
			 }
		 }
		
	 }
}
